package cn.didi.feidi.androidorder.fragment.personal;


import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.xw.repo.XEditText;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.util.AppUtil;
import cn.didi.feidi.androidorder.util.DataCheckUtil;
import cn.didi.feidi.androidorder.util.MD5Util;

public class PersonRegisterFragment extends FeidiBaseFragment {

    private static final String TAG = "PersonRegisterFragment";

    private static final int REP_SEND_SMS = 1; //重新发送
    public String country = "86";//这是中国区号，如果需要其他国家列表，可以使用getSupportedCountries();获得国家区号

    //验证码
    private String verificationCode;

    private LinearLayout inputPhoneFirstStep;
    private LinearLayout inputIdentifySecondStep;
    private LinearLayout setNewPasswordThreeStep;

    //    第一步所需控件
    private XEditText inputAccountOrPhone;
    private TextView toSecondBtn;

    //    第二步所需控件
    private XEditText inputIdentifyNumber;
    private TextView phoneNumberTip;
    private TextView reSentSmsIdentify;
    private TextView toThreeBtn;

    //    第三步所需控件
    private XEditText inputNewPassWord;
    private TextView theLastBtn;

    //    时间倒计时
    private TimerTask tt;
    private Timer tm;
    private int TIME = 60;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 1) {
//                cancelTimeCount();
//                设置重新发送按钮不可以点击
                changeResentSmsButtonClickable(false);
            } else if (msg.arg1 == 2) {
                cancelTimeCount();

//                设置重新发送按钮可以点击
                changeResentSmsButtonClickable(true);
            } else if (msg.what == REP_SEND_SMS) {
                cancelTimeCount();
                TIME = 60;//时间重置

//                设置重新发送按钮可以点击
                changeResentSmsButtonClickable(true);
            } else {
                reSentSmsIdentify.setText("重新发送" + "(" + TIME + ")");
            }
        }
    };
    //找回密码的状态 1：第一步输入手机号 或者 飞滴号 2：第二步输入验证码 3：第三步设置密码
    private int register_status = 1;
    //手机号码
    private String phoneNum;

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonRegisterFragment newInstance(Bundle bundle) {
        PersonRegisterFragment fragment = new PersonRegisterFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_person_register, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }


    @Override
    protected void initViews(View rootView) {
        inputPhoneFirstStep = (LinearLayout) rootView.findViewById(R.id.person_register_first_step);
        inputIdentifySecondStep = (LinearLayout) rootView.findViewById(R.id.person_register_second_step);
        setNewPasswordThreeStep = (LinearLayout) rootView.findViewById(R.id.person_register_three_step);

        inputAccountOrPhone = (XEditText) rootView.findViewById(R.id.person_register_input_phone_and_feidi_num);
        toSecondBtn = (TextView) rootView.findViewById(R.id.person_register_to_second_step);

        inputIdentifyNumber = (XEditText) rootView.findViewById(R.id.person_register_input_verify_num);
        phoneNumberTip = (TextView) rootView.findViewById(R.id.person_register_phone_number_tip);
        reSentSmsIdentify = (TextView) rootView.findViewById(R.id.person_register_send_verify_num_again);
        toThreeBtn = (TextView) rootView.findViewById(R.id.person_register_to_three_step);

        inputNewPassWord = (XEditText) rootView.findViewById(R.id.person_register_input_new_password);
        theLastBtn = (TextView) rootView.findViewById(R.id.person_register_the_last_tv);
    }

    @Override
    protected void initData() {
        //初始化第一步动作
        register_status = 1;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //销毁短信服务
    }

    @Override
    protected void addListener() {

        toSecondBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneNum = inputAccountOrPhone.getText().toString().trim().replaceAll("/s", "");
                if (phoneNum.length() == 0) {
                    Toast.makeText(getContext(), "输入不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!DataCheckUtil.isRightPhoneNumber(phoneNum)) {
                    makeToast("手机号格式不正确，请重新输入");
                    return;
                }

                sendSMSRequest(phoneNum);
            }
        });

        toThreeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verificationCode = inputIdentifyNumber.getText().toString().trim();
                if (verificationCode.length() != 4) {
                    Toast.makeText(getContext(), "验证码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                //  : 2017/8/8 上传验证码进行验证
                //进行请求数据整合
                Map<String, String> data = new HashMap<String, String>();
                data.put("phoneNumber", phoneNum);
                data.put("verificationCode", verificationCode);
                executeRequest(new AppActionRequest<String>(Api.REGISTER_CHECK_VERIFICATION_CODE, data, new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
                    @Override
                    public void onSuccess(String message, String data) {

                        inputIdentifySecondStep.setVisibility(View.GONE);
                        setNewPasswordThreeStep.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onFailure(int errorEvent, String message) {
                        Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                        switch (errorEvent) {
                            case ErrorEvent.WRONG_VERIFICATION_CODE:
                                makeToast("验证码不正确");
                                break;
                            case ErrorEvent.EXISTS_USER:
                                makeToast("该手机号已被注册");
                                break;
                            default:
                                makeToast("捕捉到未知错误");
                                break;
                        }
                        inputIdentifyNumber.setText("");
                    }
                }));
            }
        });

        reSentSmsIdentify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register_status = 2;
                sendSms(phoneNum);
            }
        });

        theLastBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!AppUtil.checkPassword(inputNewPassWord.getText().toString().trim())) {
                    makeToast("请输入6-16位字母和数字组合密码");
                    return;
                }
                //  : 2017/8/8 上传新密码
                //进行请求数据整合
                Map<String, String> data = new HashMap<String, String>();
                data.put("phoneNumber", phoneNum);
                data.put("password", MD5Util.GetMD5Code32Bit(inputNewPassWord.getText().toString().trim()));
                data.put("verificationCode", verificationCode);

                executeRequest(new AppActionRequest<String>(Api.REGISTER, data, new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
                    @Override
                    public void onSuccess(String message, String data) {
                        Log.d(TAG, "REGISTER success: " + message);
                        makeToast("注册成功");
                        mActivity.finish();
                    }

                    @Override
                    public void onFailure(int errorEvent, String message) {
                        Log.d(TAG, "REGISTER failure errorEvent: " + errorEvent + "message: " + message);
                        makeToast("注册失败");
                        switch (errorEvent) {
                            case ErrorEvent.WRONG_VERIFICATION_CODE:
                                makeToast("验证码不正确");
                                break;
                            case ErrorEvent.EXISTS_USER:
                                makeToast("该手机号已被注册");
                                break;
                            case ErrorEvent.WRONG_PASSWORD:
                                makeToast("密码格式不正确");
                                break;
                            default:
                                makeToast("捕捉到未知错误");
                                break;
                        }
                    }
                }));
            }
        });
    }

    /**
     * 取消时间倒计时
     */
    private void cancelTimeCount() {
        if (tm != null)
            tm.cancel();//取消任务
        if (tt != null)
            tt.cancel();//取消任务
    }

    /**
     * 发送验证码
     *
     * @param phoneNum
     */
    public void sendSms(String phoneNum) {
        switch (register_status) {
            case 1:
                // 通过sdk发送短信验证
                tm = new Timer();
                tt = new TimerTask() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessage(TIME--);
                    }
                };
                tm.schedule(tt, 0, 1000);
                break;
            case 2:
                // 通过sdk发送短信验证
                sendSMSRequest(phoneNum);
                tm = new Timer();
                tt = new TimerTask() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessage(TIME--);
                    }
                };
                tm.schedule(tt, 0, 1000);

//                设置重新发送按钮不可点击
                changeResentSmsButtonClickable(false);

                break;
            default:
                break;
        }


    }

//    private void showDialog(String content, String btnText) {
//        //弹出提示框
//        CommomDialog dialog = new CommomDialog(getContext(), R.style.dialog, content, new CommomDialog.OnCloseListener() {
//            @Override
//            public void onClick(Dialog dialog, boolean confirm) {
//                if (confirm) {
//                    //  : 2017/8/3 设置飞滴号已设置的标志 并修改
//                    Toast.makeText(getContext(),btnText,Toast.LENGTH_SHORT).show();
//                    dialog.dismiss();
//                }
//            }
//        }, true, true).setPositiveButton(btnText,"#43A5F5");
//        dialog.show();
//    }

    /**
     * 设置提交按钮是否可见
     *
     * @param isClickable
     */
    private void changeResentSmsButtonClickable(boolean isClickable) {
        if (isClickable) {
//          设置重新发送按钮的样式
            reSentSmsIdentify.setClickable(true);
            reSentSmsIdentify.setTextColor(Color.parseColor("#347cf1"));
            reSentSmsIdentify.setText("重新发送");
            reSentSmsIdentify.setBackgroundResource(R.drawable.bg_blue_corner_register);

        } else {
            reSentSmsIdentify.setClickable(false);
            reSentSmsIdentify.setTextColor(Color.parseColor("#b0cbf5"));
            reSentSmsIdentify.setBackgroundResource(R.drawable.bg_white_resent_verify);
        }
    }

    private void sendSMSRequest(final String phoneNum){
        Map<String, String> data = new HashMap<String, String>();
        data.put("phone", phoneNum);

        executeRequest(new AppActionRequest<String>(Api.REGISTER_GET_VERIFICATIONCODE, data, new TypeToken<ApiResponse<String>>() {
        }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                Message handlerMessage = mHandler.obtainMessage();
                handlerMessage.arg1 = 1;
                mHandler.sendMessage(handlerMessage);

                //后台返回成功
                sendSms(phoneNum);

                phoneNumberTip.setText("正在往" + phoneNum + "发送短信验证码");
                inputPhoneFirstStep.setVisibility(View.GONE);
                inputIdentifySecondStep.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "REGISTER failure errorEvent: " + errorEvent + "message: " + message);
                switch (errorEvent) {
                    case ErrorEvent.EXISTS_USER:
                        makeToast("该手机号已被注册");
                        break;
                    case ErrorEvent.WRONG_PHONE_NUMBER:
                        makeToast("手机号格式不对");
                        break;
                    case ErrorEvent.VERIFICATION_CODE_SAVE_ERROR:
                        makeToast("验证码保存失败");
                        break;
                    case ErrorEvent.VERIFICATION_CODE_SEND_ERROR:
                        makeToast("用户验证码发送失败");
                        break;
                    case ErrorEvent.PARAM_ACCESS_QUICK:
                        break;
                    case ErrorEvent.PARAM_ACCESS_ERROR_NET:
                        break;
                    default:
                        makeToast("捕捉到未知错误");
                        break;
                }
                Message handlerMessage = mHandler.obtainMessage();
                handlerMessage.arg1 = 2;
                mHandler.sendMessage(handlerMessage);
            }
        }));

    }
}
